#!/usr/bin/env python

import gtk # tray icon
import os
#import sys
import wmi
import win32com.client  # find adapters
import ctypes           # lock Workstation, manage mouse position
import audiere          # play wav file
#import time
#import threading
#import timer
import gobject          # check
#import pygame
import win32api, win32con   # volume

debug = True

class StatusIcc:
    def __init__(self):
        
        self.enabled = False
        self.myChecker = Checker()
        self.myWorkst = Workstation()
        
        # create a new Status Icon
        self.staticon = gtk.StatusIcon()
        self.staticon.set_from_file('antheft_disabled.ico')
        self.staticon.set_blinking(False)
        self.staticon.set_tooltip('antheft - Disabled')
        self.staticon.connect("activate", self.activate)
        self.staticon.connect("popup_menu", self.popup)
        self.staticon.set_visible(True)
        # create a new menu
        menu = '''
			<ui>
			 <menubar name="Menubar">
			  <menu action="Menu">
			   <menuitem action="Preferences"/>
			   <menuitem action="About"/>
			   <separator/>
			   <menuitem action="Close"/>
			  </menu>
			 </menubar>
			</ui>
		'''
        actions = [
			('Menu',  None, 'Menu'),
			('Preferences', gtk.STOCK_PREFERENCES, '_Preferences...', None, None, self.on_pref),
			('About', gtk.STOCK_ABOUT, '_About...', None, None, self.on_about),
			('Close', gtk.STOCK_CLOSE, '_Exit', None, None, self.on_exit)]
        ag = gtk.ActionGroup('Actions')
        ag.add_actions(actions)
        self.manager = gtk.UIManager()
        self.manager.insert_action_group(ag, 0)
        self.manager.add_ui_from_string(menu)
        self.menu = self.manager.get_widget('/Menubar/Menu/About').props.parent
    
    # popup callback
    def popup(self, status, button, time):
        self.menu.popup(None, None, None, button, time)
    
    # activate callback
    def activate( self, widget, data=None):
        if self.enabled == False:
            self.staticon.set_from_file('antheft_enabled.ico')
            self.staticon.set_tooltip('antheft - Enabled')
            self.myChecker.start()
            self.myWorkst.lock_pc()
            self.enabled = True
        else:
            self.staticon.set_from_file('antheft_disabled.ico')
            self.staticon.set_tooltip('antheft - Disabled')
            self.myChecker.stop()
            self.enabled = False
        
    # about
    def on_about(self, data):
        dialog = gtk.AboutDialog()
        dialog.set_name('antheft')
        dialog.set_version('0.0.1')
        dialog.set_comments('The best alarm system\nfor your pc. Win & Linux')
        dialog.set_website('p0l.it')
        dialog.run()
        dialog.destroy()
    
    # exit
    def on_exit(self, data):
        self.staticon.set_visible(False)
        gtk.main_quit()

    # enable
    def on_pref(self, data):
        print "Is my Workstation now locked? " + str(self.myWorkst.is_locked())
    
    #enable old
    def on_pref_(self, data):
        dialog = gtk.MessageDialog(
        parent         = None,
        flags          = gtk.DIALOG_DESTROY_WITH_PARENT,
        type           = gtk.MESSAGE_INFO,
        buttons        = gtk.BUTTONS_OK_CANCEL,
        message_format = "Do you want to close this Status Icoprogram?")
        dialog.set_title('Popup Window')
        dialog.connect('response', self.destroyer)
        dialog.show()
    # destroyer callback
    def destroyer(self, widget,response_id, data= None):
        if response_id == gtk.RESPONSE_OK:
                gtk.main_quit()
        else:
                widget.hide()



class Siren():
    def __init__(self):
        self.d = audiere.open_device()
        self.l = self.d.open_file('antheft.wav')
    def start(self):
        win32api.keybd_event(win32con.VK_VOLUME_UP, 0)
        self.l.repeating = 1
        if not self.l.playing:
            self.l.play()
    def stop(self):
        self.l.stop()



class Workstation():
    def __init__(self):
        self.DESKTOP_SWITCHDESKTOP = 0x0100
        
    # lock pc
    def lock_pc(self):
        #winpath=os.environ['windir']
        #os.system(winpath + '\\system32\\rundll32 user32.dll, LockWorkStation')
        ctypes.windll.user32.LockWorkStation()
            
    # say if the computer is locked
    def is_locked(self):
        OpenDesktop = ctypes.windll.User32.OpenDesktopA
        SwitchDesktop = ctypes.windll.User32.SwitchDesktop
        hDesktop = OpenDesktop ("default", 0, False, self.DESKTOP_SWITCHDESKTOP)
        result = SwitchDesktop (hDesktop)
        if result:
            return False
        else:
            return True



class Checker:
    def __init__(self):
        self.enabled = False
        self.alarmActivated = False
        self.myPlugin = Plug()
        self.mySiren = Siren()
        self.myMouse = Mouse()
        
    def start(self):
        self.enabled = True
        self.posMouseX, self.posMouseY = self.myMouse.getMousePos()
        self.check = gobject.timeout_add (1 * 1000, self.do_it) #avvia il check
        
    def stop(self):
        self.enabled = False
        self.alarmActivated = False
        self.mySiren.stop()
    
    def do_it(self):
        # controllo se e' tutto ok
        if (self.enabled):
            if (not self.myPlugin.is_it_all_right(self.posMouseX, self.posMouseY)):
                if (self.alarmActivated == False):
                    self.alarmActivated = True
                    self.mySiren.start()
        
        if (debug):
            print "Alarm Activated? ", self.alarmActivated
            print "Mouse position: ", self.posMouseX, self.posMouseY, ' - ', self.myMouse.getMousePos()
        
        # continuo il controllo ogni secondo
        if (self.enabled == True):
            return True # continua la chiamata...
        else:
            return False



class Plug:
    def __init__(self):
        self.myLan = LanAdapters()
        self.myMouse = Mouse()
    def is_it_all_right(self,X,Y):
        if ( self.myLan.is_plugged() and self.myMouse.is_plugged() ):
        #self.myMouse.is_still(X,Y) and
            return True
        else:
            return False



class LanAdapters:
    def __init__(self):
        self.wmi = win32com.client.GetObject('winmgmts:')
        
    def is_plugged(self):
        msg = self.eth_status(4)
        if (msg=="Up"): return True
        else: return False 
        
    def eth_status(self, adapter_id):
        self.adapter = self.wmi.InstancesOf('win32_networkadapter where DeviceId=' + str(adapter_id))[0]
        #print "Name: ", adapter.Name
        if (self.adapter.NetConnectionStatus==2): return "Up"
        elif (self.adapter.NetConnectionStatus==7): return "Down"
        else: return "Error"
        
    # stampa la lista di adapters
    def print_adapters(self):
        self.adapters=self.wmi.InstancesOf('win32_networkadapter where NetConnectionStatus=2')
        for adapter in self.adapters:
            print "Name: ", adapter.Name
            print "NetConnectionStatus: ", adapter.NetConnectionStatus
            print "DeviceID: ", adapter.DeviceID
            #print "Index: ", adapter.Index
            #print "Interf: ", adapter.InterfaceIndex
            #print "NetConnectionId: ", adapter.NetConnectionId
                
    # stampa la lista di adapters (old)
    def print_adapters_old(self):
        c=wmi.WMI()
        #o=c.query("select * from Win32_NetworkAdapter where NetConnectionStatus=2")
        # 2 attiva, 7 disattiva
        for nic in c.Win32_NetworkAdapter(NetConnectionStatus=2):
            #print nic
            print "Name: ", nic.Name
            print "NetConnectionStatus: ", nic.NetConnectionStatus
            print "NetConnectionId: ", nic.NetConnectionId



class Mouse():
    def __init__(self):
        self.wmi = win32com.client.GetObject('winmgmts:')
        
    def is_plugged(self):
        msg = self.mouse_status(162)
        if (msg=="In"): return True
        else: return False 
        
    # return mouse coordinates
    def getMousePos (self):
        class POINT(ctypes.Structure):
            _fields_ = [("x", ctypes.c_long),
                    ("y", ctypes.c_long)]
        point = POINT()
        pi = ctypes.pointer(point)
        ctypes.windll.user32.GetCursorPos(pi)
        return int(point.x), int(point.y)
        
    def is_still(self, origX, origY):
        nowX, nowY = self.getMousePos()
        if (abs(origX-nowX)<6 and abs(origY-nowY)<6):
            return True
        else:
            return False
            
    def print_mice(self):
        o=self.wmi.InstancesOf('Win32_PointingDevice')
        for objItem in o:
            print "Description: ", objItem.Description
            print "Device ID: ", objItem.DeviceID
            print "Device Interface: ", objItem.DeviceInterface
            
    def mouse_status(self, mouse_id):
        self.mouse = self.wmi.InstancesOf('Win32_PointingDevice where DeviceInterface=' + str(mouse_id))
        if (len(self.mouse)==1):
            return "In"
        else:
            return "Out"



class ACPower():
    def __init__(self):
        self.wmi = win32com.client.GetObject('winmgmts:')
    def print_power(self):
        c=wmi.WMI()
        power_watcher=c.query("select * from Win32_PowerManagementEvent")
        #power_watcher = wmi.ExecNotificationQuery ( query )
        #power_event = power_watcher.NextEvent ()
        print len(power_watcher)



if __name__ == "__main__":
    gigi = ACPower()
    gigi.print_power()
    statusicon = StatusIcc()
    gtk.main()
    
    
'''
f= os.popen('<type your dos command>')
s = f.read()
print s
'''
